
// PythonGateway.java
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import py4j.GatewayServer;

public class PythonGateway {
	public int multiply(int a, int b) {
		return a * b;
	}

	public static String checkConnectOpenGaussDatabase(String url, String user, String password) {
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		String return_string = "";
		String error_string = "";

		int code = 0;
		int count = 0;
		String msg = "";
		String returnJsonString = "";

		try {
			Class.forName("com.huawei.opengauss.jdbc.Driver");
			connection = DriverManager.getConnection(url, user, password);
			System.out.println("【INFO】: ✅ 成功连接到 openGauss 数据库！" + "{\"url\":\"" + url + "\",\"user\":\"" + user
					+ "\",\"password\":\"" + password + "\"}");
			return_string += "【INFO】:✅ 成功连接到 openGauss 数据库！" + "{\"url\":\"" + url + "\",\"user\":\"" + user
					+ "\",\"password\":\"" + password + "\"}" + "\n";
			statement = connection.createStatement();
			String sql = "SELECT version()";
			resultSet = statement.executeQuery(sql);
			while (resultSet.next()) {
				System.out.println("【INFO】:Database Version: " + resultSet.getString(1));
				return_string += "【INFO】:Database Version: " + resultSet.getString(1) + "\n";
			}
			code = 1;
			msg = return_string;
			returnJsonString = formatJsonString(code, count, msg, new JSONArray());
			// return returnJsonString;
		} catch (ClassNotFoundException e) {
			error_string = "【ClassNotFoundException（类未找到异常）】: ❌ 未找到 openGauss JDBC 驱动，请检查 JAR 是否加入类路径！";
			System.err.println(error_string);
			e.printStackTrace();
			return_string += error_string + "\n";
			// code = -1;
			msg = return_string;
			returnJsonString = formatJsonString(code, count, msg, new JSONArray());
			// return returnJsonString;
		} catch (SQLException e) {
			error_string = "【SQLException（SQL异常）】:❌ 数据库连接或操作失败！";
			System.err.println(error_string);
			e.printStackTrace();
			return_string += error_string + "\n" + e.getClass().getName() + " - " + e.getMessage();
			// code = -1;
			msg = return_string;
			returnJsonString = formatJsonString(code, count, msg, new JSONArray());
			// return returnJsonString;
		} finally {
			try {
				if (resultSet != null)
					resultSet.close();
				if (statement != null)
					statement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return returnJsonString;
	}

	public static String executeQueryToJsonString(String url, String user, String password, String sql) {
		OpenGaussUtil dbUtil = new OpenGaussUtil(url, user, password);
		String resultString = "";
		try {
			dbUtil.connect();
			resultString = dbUtil.executeQuery(sql);
			System.out.println("Query Result:\n" + resultString);
		} catch (SQLException e) {
			e.printStackTrace();
			resultString = "【SQLException（SQL异常）】:❌" + e.getClass().getName() + " - " + e.getMessage();
			// System.out.println("【SQLException（SQL异常）】:❌ " + e.getMessage());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			resultString = "【ClassNotFoundException（类未找到异常）】:❌" + e.getClass().getName() + " - " + e.getMessage();
			// System.out.println("【SQLException（SQL异常）】:❌ " + e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			resultString = "【Exception（未知异常）】:❌ " + e.getClass().getName() + " - " + e.getMessage();
		} finally {
			try {
				dbUtil.disconnect();
			} catch (Exception e) {
				e.printStackTrace();
				resultString = "【Exception（未知异常）】: " + e.getClass().getName() + " - " + e.getMessage();
			}
		}
		return resultString;
	}

	public static String executeInsertUpdateDelete(String url, String user, String password, String sql) {
		OpenGaussUtil dbUtil = new OpenGaussUtil(url, user, password);
		String resultString = "";
		try {
			dbUtil.connect();
			resultString = dbUtil.executeUpdate(sql);
			System.out.println(resultString);
		} catch (SQLException e) {
			e.printStackTrace();
			resultString = "【SQLException（SQL异常）】:❌" + e.getClass().getName() + " - " + e.getMessage();
			// System.out.println("【SQLException（SQL异常）】:❌ " + e.getMessage());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			resultString = "【ClassNotFoundException（类未找到异常）】:❌" + e.getClass().getName() + " - " + e.getMessage();
			// System.out.println("【SQLException（SQL异常）】:❌ " + e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			resultString = "【Exception（未知异常）】: " + e.getClass().getName() + " - " + e.getMessage();
		} finally {
			try {
				dbUtil.disconnect();
			} catch (Exception ex) {
				ex.printStackTrace();
				resultString = "【Exception（未知异常）】: " + ex.getClass().getName() + " - " + ex.getMessage();
			}
		}
		return resultString;
	}

	// 格式化json字符串返回格式
	private static String formatJsonString(int code, int count, String msg, JSONArray data) {
		JSONObject totalJsonObject = new JSONObject();
		totalJsonObject.put("code", code);
		totalJsonObject.put("count", count);
		totalJsonObject.put("msg", msg);
		totalJsonObject.put("data", data);
		return totalJsonObject.toJSONString();
	}

	public static void main(String[] args) throws UnknownHostException {
		PythonGateway gateway = new PythonGateway();
		// 获取本机的IP
		// String ipAddress = InetAddress.getLocalHost().getHostAddress();
		int port = 25333;
		GatewayServer server = new GatewayServer(gateway, // 入口对象（可自定义）
				port, // 端口号
				GatewayServer.DEFAULT_CONNECT_TIMEOUT, GatewayServer.DEFAULT_READ_TIMEOUT // 关键：绑定到指定IP
		);
		server.start();
		System.out.println("【INFO】:Gateway Server started on port " + port);
		System.out.println("【INFO】:Entry point: " + server.getGateway().getEntryPoint());

	}
}